package com.forlove.app.qselect.login.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.CipherUtils;
import com.forlove.app.common.utils.CryptAES;
import com.forlove.app.common.utils.LocationUtils;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.manager.ContactsManager;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.UpLoadContactsAsync;
import com.forlove.app.qselect.login.entity.ContactsInfoEntity;
import com.forlove.app.qselect.login.entity.LoginEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.presenter.LoginInputPwPresenter;
import com.forlove.app.qselect.login.view.ILoginInputPWView;
import com.forlove.app.qselect.login.widget.ErrorMessageView;
import com.forlove.app.qselect.login.widget.ResetPwTipDialog;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

/**
 * 登录输入密码页面
 * Created by yjl on 2017/10/18.
 */

public class LoginInputPWActivity extends BaseActivity implements View.OnClickListener, ILoginInputPWView {
    public static final String FORGET_PW = "forgot_pw";
    @BindView(R.id.edittext_input_pw)
    AppCompatEditText edittext_input_pw;

    @BindView(R.id.bt_login_nextstep)
    TextView bt_login_nextstep;

    @BindView(R.id.view_error_message)
    ErrorMessageView view_error_message;

    @BindView(R.id.text_forgot_pw)
    TextView text_forgot_pw;

    @BindView(R.id.image_user_photo)
    CircleImageView image_user_photo;

    private String phonePW;//密码
    private LoginEntity loginEntity;

    private UserEntity mUser;
    private LoginInputPwPresenter loginInputPwPresenter;
    private ResetPwTipDialog resetPwTipDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login_input_pw;
    }

    @Override
    public void initView() {
        loginInputPwPresenter = new LoginInputPwPresenter(this);
        initEditText();
        bt_login_nextstep.setOnClickListener(this);
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            mUser = (UserEntity) bundle.getSerializable("userinfo");
        }
        if (mUser == null) {
            LogUtil.e("yjl", "userEntity is null");
            finish();
        } else {
            loginInputPwPresenter.loadImageView(this,
                    image_user_photo, mUser.mUserImage,
                    R.mipmap.image_mine_friend_avatar);
        }

        text_forgot_pw.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        StatusBarCompat.compat(this, Color.parseColor("#ffffff"));
    }

    private void showResetPwTipDialog() {
        if (resetPwTipDialog == null) {
            resetPwTipDialog = new ResetPwTipDialog(this);
        }
        if (mUser != null && !TextUtils.isEmpty(mUser.userMobile)) {
            int lenght = mUser.userMobile.length();
            if (lenght > 5) {
                String str = mUser.userMobile.substring(0, 3);
                for (int i = 0; i < (lenght - 3); i++) {
                    str += "*";
                }
                resetPwTipDialog.setTextMesseage("将要发送验证短信到手机号为" + str);
            }
        }
        resetPwTipDialog.setAgreeListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestResetPWPhone();
                resetPwTipDialog.dismiss();
            }
        });
        resetPwTipDialog.show();
    }

    /**
     * 遗忘，重置密码
     */
    private void requestResetPWPhone() {

        loginEntity = new LoginEntity();
        loginEntity.mobile = mUser.userMobile;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(loginEntity.mobile);
//        String aesPw = CipherUtils.md5();
        String time = MyTimeUtils.formatDate(new Date(System.currentTimeMillis()), "yyyyMMdd");
        stringBuilder.append(time);
//        LogUtil.e("yjl", "明文:" + stringBuilder.toString());
        String keyCode = CipherUtils.md5(stringBuilder.toString());
        String sign = CryptAES.AES_Encrypt(keyCode, loginEntity.mobile);
        loginInputPwPresenter.loadSendMsg(loginEntity, sign);
    }

    private void initEditText() {
        edittext_input_pw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s)) {
                    bt_login_nextstep.setBackground(getResources().getDrawable(R.drawable.bt_register_nextstep_selector));
                } else {
                    bt_login_nextstep.setBackground(getResources().getDrawable(R.drawable.bg_register_nextstep_corner_sel));
                }
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login_nextstep:
                requestCheckPW();
                break;
            case R.id.text_forgot_pw:
                //TODO 忘记密码
                showResetPwTipDialog();
                break;
        }
    }

    private void requestCheckPW() {
        phonePW = edittext_input_pw.getText().toString();
        if (TextUtils.isEmpty(phonePW)) {
            view_error_message.setError("请输入登录密码");
            view_error_message.setVisibility(View.VISIBLE);
            return;
        }
        loginEntity = new LoginEntity();
        loginEntity.mobile = mUser.userMobile;
        loginEntity.mobile_type = "android";
        loginEntity.location = LocationUtils.getBestLocationString(this);
        loginEntity.password = CipherUtils.md5(phonePW);
        loginInputPwPresenter.loadLoginPwData(loginEntity);
    }

    @Override
    protected void onDestroy() {
        if (resetPwTipDialog != null) {
            resetPwTipDialog.dismiss();
        }
        resetPwTipDialog = null;
        super.onDestroy();
        getSupportLoaderManager().destroyLoader(UpLoadContactsAsync.ASYNC_ID);
    }

    @Override
    public void checkPWView(final NetworkManager.ResultCode resultCode, final UserEntity userEntity, final String msg) {
        if (NetworkManager.ResultCode.RESULT_ERROR.equals(resultCode)
                || NetworkManager.ResultCode.RESULT_FAIL.equals(resultCode)) {
            view_error_message.setError(msg);
            view_error_message.setVisibility(View.VISIBLE);
        } else if (NetworkManager.ResultCode.RESULT_SUCCESS.equals(resultCode) && userEntity != null) {
            userEntity.regId = UserManager.getJPushID(this);
            UserManager.saveLoginState(this, true);
            UserManager.saveUserInfo(this, userEntity);
            Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show();
            if (!TextUtils.isEmpty(userEntity.regId)) {
                loginInputPwPresenter.loadUpJPushRegisterId(new HashMap());
            }
            getSupportLoaderManager().restartLoader(UpLoadContactsAsync.ASYNC_ID, null, new LoaderManager.LoaderCallbacks<List<ContactsInfoEntity>>() {

                @Override
                public Loader<List<ContactsInfoEntity>> onCreateLoader(int id, Bundle args) {
                    return new UpLoadContactsAsync(LoginInputPWActivity.this);
                }

                @Override
                public void onLoadFinished(Loader<List<ContactsInfoEntity>> loader, List<ContactsInfoEntity> data) {
                    if (data.size() > 0) {
                        ContactsManager.saveContactsFriend(LoginInputPWActivity.this, data);
                    }
                }

                @Override
                public void onLoaderReset(Loader<List<ContactsInfoEntity>> loader) {

                }
            });
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//            startActivity(intent);
            toMainActivity();
            finish();
        }

    }

    @Override
    public void showSendMsgView(LoginEntity loginEntity) {
        Toast.makeText(this, "发送成功", Toast.LENGTH_SHORT).show();
        if (loginEntity != null && !TextUtils.isEmpty(loginEntity.message)) {
            Toast.makeText(this, loginEntity.message, Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, ValidateCodeActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString("phone", mUser.userMobile);
            intent.putExtras(bundle);
            startActivity(intent);
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                view_error_message.showErrorMsg(msg);
            }
        });

    }
}
